#include <stdio.h>

#include "security.h"
#include "security_error.h"

#include "mbedtls/base64.h"

int security_base64_encode(char out[], size_t *olen, size_t osize, char in[], size_t inlen) {
    int ret = 0;

    if(out == NULL || olen == NULL || in == NULL) {
        return SECURITY_ERR_POINTER_NULL;
    }

    if(osize == 0 || inlen == 0) {
        return SECURITY_ERR_BAD_INPUT;
    }

    ret = mbedtls_base64_encode(out, osize, olen, in, inlen);
    switch (ret) {
    case 0:
        return SECURITY_OK;

    case MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL:
        return SECURITY_ERR_BUFFER_TOO_SMALL;

    case MBEDTLS_ERR_BASE64_INVALID_CHARACTER:
        return SECURITY_BASE64_INVALID_CHARACTER;
    }

    return SECURITY_UNKNOW;
}

int security_base64_decode(char out[], size_t *olen, size_t osize, char in[], size_t inlen) {
    int ret = 0;

    if(out == NULL || olen == NULL || in == NULL) {
        return SECURITY_ERR_POINTER_NULL;
    }

    if(osize == 0 || inlen == 0) {
        return SECURITY_ERR_BAD_INPUT;
    }

    ret = mbedtls_base64_decode(out, osize, olen, in, inlen);
    switch (ret)
    {
    case 0:
        return SECURITY_OK;

    case MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL:
        return SECURITY_ERR_BUFFER_TOO_SMALL;

    case MBEDTLS_ERR_BASE64_INVALID_CHARACTER:
        return SECURITY_BASE64_INVALID_CHARACTER;    
    }

    return SECURITY_UNKNOW;
}